<?php

namespace App\Exports;

use App\Models\Constant\OrderConstant;
use App\Models\Order\Order;
use App\Models\User\LiPei;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;

class OrderExport extends DefaultValueBinder implements FromArray,WithCustomValueBinder
{

    private $conditions;

    public function __construct(array $conditions) {
        $this->conditions = $conditions;
    }

    public function array():array  {
        $data = [
             [
                'ID',
                '立案号',
                 '出险时间',
                 '被保险人',
                '车牌号',
                '车架号',
                 '定损金额',
                 '赔付金额',
                '状态',
                '收款户名',
                '收款银行',
                '收款账号',
                 '创建时间',
                 '维修工厂',
                '维修方式',


            ]
        ];


        $cols = ['id','case_number','chu_xian_date','bao_xian_name','car_number','car_jia_number','ding_sun_price','real_ding_sun_price',
            'status','repair_factory_id','bank_account_name','bank_type','bank_card','created_at'];
        $records = (new Order())->getLst($this->conditions)->where('status',OrderConstant::STATUS_END)->with('getRepairFactory');
        if(!empty($this->conditions['repairFactoryName'])){
            $records = $records->whereHas('getRepairFactory',function ($q){
                $q->where('name','like',"%".$this->conditions['repairFactoryName']."%");
            });
        }
        $records = $records->get($cols);

        foreach ($records as $record) {
            $record->status = '已完成';
            $record->reapir_factory_name = $record->getRepairFactory->name??'未知';
            $record->repair_way = $record->repair_factory_id==0?'自主维修':'指定维修';
            $record = $record->toArray();
            unset($record['repair_factory_id']);
            unset($record['get_repair_factory']);

            $data[] = $record;
        }
        Log::info('ex',$data);
        return $data;
    }

    public function bindValue(Cell $cell, $value) {

        if (is_string($value) && strlen($value) > 10) {
            $cell->setValueExplicit($value, DataType::TYPE_STRING);
            return true;
        }
        return parent::bindValue($cell, $value);
    }

}
